/*
 * Copyright 2006-2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.martinimix.dao;

import com.bluemartini.dna.DNAList;
import com.bluemartini.dna.DNAStringArray;

/**
 * Provides input for a chain of business actions.
 * 
 * @author Scott Rossillo
 *
 */
public class BusinessActionChainInput {
	
	private final static String BM_RESPONSE = "__BMRESPONSE__";
	
	private final DNAList request;
	
	/**
	 * Constructs a new chain input with the given initial input.
	 * 
	 * @param input a <code>DNAList</code> containing the initial input
	 * for this chain
	 */
	public BusinessActionChainInput(DNAList input) {
		
		if(input == null) {
			throw new NullPointerException("[input] cannot be null!");
		}
		
		request = input;
	}
	
	/**
	 * Returns this chain's current request.
	 * 
	 * @return a <code>DNAList</code> containing the current
	 * request state
	 */
	public DNAList getRequest() {
		return request;
	}
	
	/**
	 * Updates the state of this chain based on the given business action
	 * response.
	 * 
	 * @param response
	 */
	public void update(DNAList response) {

		DNAList bmResponse = response.removeList(BM_RESPONSE);
		
		if(bmResponse != null) {
			removeData(bmResponse.removeStringArray("removed"));
		}
		
		request.merge(response, DNAList.MERGE_ARRAYS_MERGE);
	}
	
	private void removeData(DNAStringArray removed) {
		
		if(removed == null) {
			return;
		}
		
		for(int i = 0; i < removed.size(); i++) {
			removeData(removed.elementAt(i));
		}
	}

	private void removeData(String name) {
		
		if(name == null) {
			return;
		}
		
		String[] parts = name.split("<>");
		DNAStringArray path = new DNAStringArray(parts.length);
		
		for(int i = 0; i < parts.length; i++) {
			path.addElement(parts[i]);
		}
		
		request.setBasePairRef(path, null);
	}
	
}
